<script lang="ts" setup>
import type { SystemRoleApi } from '#/api/system/role';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage, ElTree } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { getMenuList, rootMenu, SystemMenuApi } from '#/api/system/menu';
import { assignRoleMenu, getRoleMenuList } from '#/api/system/permission';
import { $t } from '#/locales';

import { useMenuFormSchema } from '../data';

const emit = defineEmits(['success']);
const menuTreeRef = ref<InstanceType<typeof ElTree>>();
const menuTree = ref<SystemMenuApi.SystemMenu[]>([]); // 菜单树
const menuLoading = ref(false); // 加载菜单列表
// const isAllSelected = ref(false); // 全选状态
// const isExpanded = ref(false); // 展开状态
// const expandedKeys = ref<number[]>([]); // 展开的节点
const defaultExpandedKeys = ref<number[]>([-1]); // 默认展开
const defaultCheckedKeys = ref<number[]>([]); // 默认选中
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: useMenuFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = await formApi.getValues();
    try {
      const dataTree = (menuTreeRef.value!.getCheckedKeys(false) ?? []).map(
        Number,
      );
      await assignRoleMenu({
        roleId: data.roleId,
        menuIds: dataTree,
      });
      // 关闭并提示
      await modalApi.close();
      emit('success');
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<SystemRoleApi.SystemRole>();
    if (!data || !data.roleId) {
      return;
    }
    modalApi.lock();
    try {
      await formApi.setValues(data);

      // 加载角色菜单
      const menuIds = await getRoleMenuList(data.roleId as number);

      await formApi.setFieldValue('menuIds', menuIds);
      // 加载菜单列表
      await loadMenuTree(menuIds);
    } finally {
      modalApi.lock(false);
    }
  },
});

/** 加载菜单树 */
async function loadMenuTree(menuIds: []) {
  menuLoading.value = true;
  try {
    const data = await getMenuList();
    rootMenu.children = data;
    menuTree.value = [rootMenu];
    defaultCheckedKeys.value = menuIds;
  } finally {
    menuLoading.value = false;
  }
}

// 字段映射配置
const treeProps = {
  label: (data: any) => data.meta.title, // 通过函数返回
  children: 'children',
};
</script>

<template>
  <Modal title="菜单权限">
    <Form class="mx-4">
      <template #menuIds>
        <!-- TODO @芋艿：可优化，使用 antd 的 tree？原因是，更原生 -->
        <ElTree
          :data="menuTree"
          ref="menuTreeRef"
          show-checkbox
          node-key="id"
          :default-expanded-keys="defaultExpandedKeys"
          :default-checked-keys="defaultCheckedKeys"
          :props="treeProps"
        >
          <template #default="{ node }">
            <span>{{ node.label }}</span>
          </template>
        </ElTree>
      </template>
    </Form>
    <template #prepend-footer>
      <!-- <div class="flex flex-auto items-center">
        <ElCheckbox :checked="isAllSelected" @change="toggleSelectAll">
          全选
        </ElCheckbox>
        <ElCheckbox :checked="isExpanded" @change="toggleExpandAll">
          全部展开
        </ElCheckbox>
      </div> -->
    </template>
  </Modal>
</template>
